import 'package:dio/dio.dart';
import 'response.dart';
class JMNetError implements Exception {
  final int code;
  final String message;
  final dynamic data;

  JMNetError(this.code, this.message, {this.data});

  factory JMNetError.create(DioException error) {
    var response = error.response;
    var code = response?.statusCode ?? -1;
    var data = JMNetResponse(
      code: response?.statusCode,
      msg: response?.statusMessage,
      data: response?.data,
      extra: response.toString(),
    );

    switch (error.type) {
      case DioExceptionType.cancel:
        {
          return JMNetError(code, "请求取消", data: data);
        }
      case DioExceptionType.connectionTimeout:
        {
          return JMNetError(code, "连接超时", data: data);
        }
      case DioExceptionType.sendTimeout:
        {
          return JMNetError(code, "请求超时", data: data);
        }
      case DioExceptionType.receiveTimeout:
        {
          return JMNetError(code, "响应超时", data: data);
        }
      case DioExceptionType.badResponse:
        {
          var errCode = error.response?.statusCode;
          switch (errCode) {
            case 400:
              return JMNetError(code, "请求语法错误", data: data);
            case 401:
              return JMNetError(code, "没有权限", data: data);
            case 403:
              return JMNetError(code, "服务器拒绝执行", data: data);

            case 404:
              return JMNetError(code, "无法连接服务器", data: data);

            case 405:
              return JMNetError(code, "请求方法被禁止", data: data);

            case 500:
              return JMNetError(code, "服务器内部错误", data: data);

            case 502:
              return JMNetError(code, "无效的请求", data: data);

            case 503:
              return JMNetError(code, "服务器挂了", data: data);

            case 505:
              return JMNetError(code, "不支持HTTP协议请求", data: data);

            default:
              return JMNetError(code, error.response?.statusMessage ?? '', data: data);
          }
        }
      default:
        return JMNetError(code, '请求出错，请稍后重试！', data: data);
    }
  }
}
